<template>
  <div class="main">
    <div class="air-column">
      <h2>剩机人</h2>
      <el-form
        ref="usersForm"
        class="member-info"
        :model="{
          users: users
        }"
      >
        <div
          class="member-info-item"
          v-for="(item, index) in users"
          :key="index"
        >
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="{
              required: true,
              message: '请输入乘机人姓名',
              trigger: 'blur'
            }"
          >
            <el-input
              placeholder="姓名"
              class="input-with-select"
              v-model="item.username"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
              {
                required: true,
                message: '请输入乘机人身份证号码',
                trigger: 'blur'
              },
              {
                pattern: /^\d{18}$/,
                message: '身份证不合法',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              placeholder="证件号码"
              class="input-with-select"
              v-model="item.id"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <div
          class="insurance-item"
          v-for="item in data.insurances"
          :key="item.id"
        >
          <el-checkbox-group v-model="insuranceList">
            <el-checkbox :label="item.id">
              {{
                `${item.type}：￥${item.price}/份×${users.length}  最高赔付${item.compensation}`
              }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          ref="contactForm"
          label-width="68px"
          :rules="rules"
          :model="{
            contactName,
            contactPhone,
            captcha
          }"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input v-model="contactPhone" placeholder="请输入内容">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          v-if="$store.state.user.userInfo.token"
          type="warning"
          class="submit"
          @click="handleSubmit"
          >提交订单</el-button
        >
        <div v-else class="container">
          <!-- 主要内容 -->
          <el-row type="flex" justify="center" align="middle" class="main">
            <div class="form-wrapper">
              <!-- 表单头部tab -->
              <el-row type="flex" justify="center" class="tabs">
                <span
                  :class="{ active: currentTab === index }"
                  v-for="(item, index) in [`登录`, `注册`]"
                  :key="index"
                  @click="handleChangeTab(index)"
                >
                  {{ item }}
                </span>
              </el-row>

              <!-- 登录功能组件 -->
              <LoginForm v-if="currentTab == 0" />

              <!-- 注册功能组件 -->
              <RegisterForm @login="currentTab = 0" v-if="currentTab == 1" />
            </div>
          </el-row>
        </div>
      </div>
    </div>
    <div style="display:none">{{ totalPrice }}</div>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";
import RegisterForm from "@/components/user/RegisterForm";
export default {
  props: {
    data: Object
  },
  components: {
    LoginForm,
    RegisterForm
  },
  data() {
    return {
      users: [
        {
          username: "",
          id: ""
        }
      ],
      currentTab: 0,
      // 保险选项数据
      insuranceList: [],
      contactName: "", // 联系人姓名
      contactPhone: "", // 联系人电话
      captcha: "", // 验证码
      rules: {
        contactName: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "请输入联系人电话", trigger: "blur" },
          { pattern: /^\d{11}/, message: "输入电话格式有误", trigger: "blur" }
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      }
    };
  },
  computed: {
    totalPrice() {
      // 1.加上所有乘机人的机票钱
      let res = 0;
      // 机票价格为 this.data.seat_infos.org_settle_price
      res += this.data.seat_infos.org_settle_price * this.users.length;
      // 2.计算所有乘机人的保险钱
      // 遍历保险，如果发现id 存在于被选中的列表中，就要乘以乘机人的数量添加到结果中
      this.data.insurances.forEach(item => {
        if (this.insuranceList.indexOf(item.id) >= 0) {
          res += item.price * this.users.length;
        }
      });
      console.log("价格" + res);
      this.$emit("setToalPrice", res);
      return res;
    }
  },
  watch: {
    //   // 对于watch 监听的声明来说，如果只有一个函数没有其他选项需要声明
    //   // 那么直接写函数就可以了
    //   // 如果有其他属性需要设置比如需要深度监听 声明就是一个对象，原来的函数被套在handler 属性里面
    //   // deep 跟 immediate 是监听器的两个属性
    //   // deep 深度监听, 主要是解决, 对于一些对象内部属性变化无法监听的问题
    //   // immediate 是告诉监听器一进来就马上运行一次
    //   // 监听users数据和保险数据有变化的时候计算总价格
    //   users: {
    //     handler() {
    //       this.calcTotalPrice();
    //     },
    //     // 设置 immediate 可以让监听器一开始就执行一次
    //     immediate: true
    //   },
    //   insuranceList: {
    //     handler() {
    //       console.log("保险发生了变化");
    //       // 每当保险发生了变化, 需要重新计算一个总价格
    //       this.calcTotalPrice();
    //     },
    //     immediate: true
    //   }
    // },
    // mounted() {
    //   // 一进来就调用一次计算总价的方法,
    //   // 可以避免数据变化后监听器才出发的问题
    //   this.calcTotalPrice();
  },
  methods: {
    handleChangeTab(index) {
      this.currentTab = index;
    },
    // 计算总价格的函数
    // calcTotalPrice() {
    //   // 1.加上所有乘机人的机票钱
    //   let res = 0;
    //   // 机票价格为 this.data.seat_infos.org_settle_price
    //   res += this.data.seat_infos.org_settle_price * this.users.length;
    //   // 2.计算所有乘机人的保险钱
    //   // 遍历保险，如果发现id 存在于被选中的列表中，就要乘以乘机人的数量添加到结果中
    //   this.data.insurances.forEach(item => {
    //     if (this.insuranceList.indexOf(item.id) > 0) {
    //       res += item.price * this.users.length;
    //     }
    //   });
    //   console.log("价格" + res);
    //   this.$emit("setToalPrice", res);
    // },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        usernmae: "",
        id: ""
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      if (!this.contactPhone) {
        this.$message("请输入手机号");
        return;
      }
      this.$store.dispatch("user/sendCaptchag", this.contactPhone).then(res => {
        this.$message.success("验证码为" + res);
      });
    },

    // 提交订单
    async handleSubmit() {
      // this.$refs.usersForm.validate().then(res=>{})
      let usersForm = await this.$refs.usersForm.validate().catch(res => {});
      let contactForm = await this.$refs.contactForm
        .validate()
        .catch(res => {});
      if (usersForm && contactForm) {
        // 1. 拼接订单数据
        let data = {
          users: this.users,
          insurances: this.insuranceList,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: false,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id,
          captcha: this.captcha
        };

        //2. 提交订单
        this.$axios({
          method: "post",
          url: "/airorders",
          data,
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token
          }
        }).then(res => {
          console.log(res.data.data.id);
          const { message } = res.data;
          this.$message.success(message);
          this.$router.push(`/air/pay?id=${res.data.data.id}`);
        });
      }
    }
  }
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
.member-info[data-v-3f9c3b02] .el-form-item {
  margin-bottom: 22px;
}

.container {
  .main {
    height: 100%;
    margin: 0 auto;
    position: relative;

    .form-wrapper {
      width: 400px;
      margin: 0 auto;
      background: #fff;
      box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .tabs {
        span {
          display: block;
          width: 50%;
          height: 50px;
          box-sizing: border-box;
          border-top: 2px #eee solid;
          background: #eee;
          line-height: 48px;
          text-align: center;
          cursor: pointer;
          color: #666;

          &.active {
            color: orange;
            border-top-color: orange;
            background: #fff;
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>
